package com.bg.rpc.utils;

import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @Auther: zhengshunzhi
 * @Date: 2018/8/28 18:42
 * @Description:
 */
public class IpUtils {
    private  IpUtils (){}

    /**
     * 功能描述: 获取当前的ip地址
     * @param:
     * @return:
     * @auther: bonree
     * @date: 2018/8/28 18:47
     */
    public static InetAddress getCurrentIp() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) networkInterfaces.nextElement();
                Enumeration<InetAddress> nias = ni.getInetAddresses();
                while (nias.hasMoreElements()) {
                    InetAddress ia = (InetAddress) nias.nextElement();
                    if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
                        return ia;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args)  {
        System.out.println(getCurrentIp().getHostAddress());
    }
}
